<template>
    <div>
        <div class="time">用时: <time-format :time="costTime" /></div>
        <div class="game">
            <div class="game_box" :style="boxStyle">
                <div class="game_line" v-for="(item, index) in lineBlock" :key="`line_${index}`">
                    <div :class="`game_block ${block ? 'game_block_black' : ''}`" v-for="(block, itemize) in item"
                        :key="`line_${index}_${itemize}`" @click="changeColor(index, itemize)"></div>
                </div>
            </div>
        </div>
    </div>
</template>

<style lang="less" scoped>
@import "./index.less";
</style>


<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue"
import { type CSSProperties } from "vue"
import TimeFormat from "../TimeCounter/index.vue"
const LINE_BLOCK_SIZE = 4
let gameTimer: any = null;
const props = withDefaults(defineProps<{
    show: boolean
}>(), {
    show: false
})
/** 游戏用时 */
const costTime = ref<number>(0)
const emit = defineEmits(["update:show"])
/** 游戏是否结束 */
const isGameOver = ref<boolean>(true);
/** 游戏壳子高度 */
const boxStyle = reactive<CSSProperties>({
    top: '-150px'
})
/** 方块数组 */
const lineBlock = ref<Array<Array<boolean>>>([])
/** 添加方块盒子逻辑 */
const addBlockBox = () => {
    const index = Math.floor(Math.random() * (LINE_BLOCK_SIZE));
    const line = new Array(LINE_BLOCK_SIZE).fill(false).map((_, curr) => curr == index)
    lineBlock.value.unshift(line)
}
/** 点击方块儿 */
const changeColor = (f_index: number, e_index: number) => {
    if (isGameOver.value) return;
    if (!lineBlock.value[f_index][e_index]) {
        gameOver()
        return
    }
    lineBlock.value[f_index][e_index] = false
}
/** 结束游戏 */
const gameOver = () => {
    clearInterval(gameTimer)
    gameTimer = null
    isGameOver.value = true
    setTimeout(() => {
        alert(`游戏结束!您最后坚持了${Math.floor(costTime.value/1000)}秒`)
        emit("update:show", false)
    }, 50);

}
/** 开始游戏 */
const gameStart = () => {
    costTime.value = 0;
    isGameOver.value = false;
    addBlockBox();
    gameTimer = setInterval(() => {
        let currTop = Math.min(Number(String(boxStyle.top).replace("px", "")) + 3 + Math.floor(costTime.value / 1000), 0)
        boxStyle.top = currTop + 'px'
        if (currTop >= 0) {
            if (lineBlock.value.length >= LINE_BLOCK_SIZE) {
                if (checkGameOver()) {
                    gameOver()
                }
            }
            if (lineBlock.value.length == LINE_BLOCK_SIZE + 2) {
                lineBlock.value.pop();
            }
            boxStyle.top = '-150px'
            addBlockBox()
        }
        costTime.value += 50;
    }, 50)
}
/** 判断游戏是否结束 */
const checkGameOver = (): boolean => {
    const last = lineBlock.value[LINE_BLOCK_SIZE - 1]
    return last.some(item => item)
}
onMounted(() => {
    gameStart()
})
</script>